package org.lc.httpcollector.tool

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import org.lc.httpcollector.findKeys
import org.lc.httpcollector.model.Response
import org.lc.httpcollector.model.Server

object RedfishUtil {
    fun parseNextUrls(body: String?): List<String> =
        if (body.isNullOrEmpty()) emptyList() else findTargetValues(JSON.parseObject(body), findKeys)

    private fun findTargetValues(json: JSONObject, keys: Collection<String>): List<String> {
        val urls = mutableListOf<String>()
        for (key in json.keys) {
            if (key in keys) {
                json.getString(key)?.let { urls.add(it) }
                continue
            }
            val obj = json[key] ?: continue
            when (obj) {
                is JSONObject -> urls.addAll(findTargetValues(obj, keys))
                is JSONArray -> urls.addAll(findTargetValues(obj, keys))
            }
        }
        return urls
    }

    private fun findTargetValues(json: JSONArray, keys: Collection<String>): List<String> {
        val urls = mutableListOf<String>()
        json.forEach {
            when (it) {
                is JSONObject -> urls.addAll(findTargetValues(it, keys))
                is JSONArray -> urls.addAll(findTargetValues(it, keys))
            }
        }
        return urls
    }

    fun accept(server: Server, url: String, response: Response): Boolean {
        val innerError = response.innerError
        if (innerError != null) {
            log.error("failed to send request: ${server.ip}, $url, $innerError", innerError.e)
            return false
        }
        if (!response.success) {
            log.warn("http code is not success: ${server.ip}, $url, ${response.code}")
        }
        return true
    }

    private val log = logger()
}